﻿using Microsoft.AspNetCore.Http;
using System.Diagnostics;
using System.Threading.Tasks;
using XTemplate.Core.Model;

namespace XTemplate.Core.Middlewares
{
    public class RequestMonitorMiddleware
    {
        private readonly RequestDelegate _next;

        public RequestMonitorMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            var profiler = new Stopwatch();

            string body = "";

            context.Request.EnableBuffering();
            using var sr = new System.IO.StreamReader(context.Request.Body);
            body += $", Body: {sr.ReadToEnd()}";
            context.Request.Body.Position = 0;

            profiler.Start();
            await _next(context);
            profiler.Stop();

            // 获取客户端IP地址
            var clientIP = context.Request.HttpContext.Connection.RemoteIpAddress;
            // 获取客户端访问端口号
            var clientPort = context.Request.HttpContext.Connection.RemotePort;

            var msg = $"{context.Request.Method}, Path:{context.Request.Path}, ElapsedMilliseconds:{profiler.ElapsedMilliseconds}ms, {context.Request.ContentType} {context.Response.StatusCode}";

            msg += $", Headers: {Newtonsoft.Json.JsonConvert.SerializeObject(context.Request.Headers)}";
            if (!string.IsNullOrEmpty(context.Request.QueryString.ToString()))
                msg += $", QueryString: {context.Request.QueryString}";
            msg += body;
            //if (context.Request.Form != null)
            //    msg += $", Form: {Newtonsoft.Json.JsonConvert.SerializeObject(context.Request.Form)}";
            if (context.Response.StatusCode >= 400)
            {
                NLog.LogManager.GetCurrentClassLogger().WithProperty("remote-ip", $"{clientIP}:{clientPort}").Warn(msg);
            }
            else
                NLog.LogManager.GetCurrentClassLogger().WithProperty("remote-ip", $"{clientIP}:{clientPort}").Info(msg);

            if (context.Response.StatusCode == 404)
                await context.Response.WriteAsync(Newtonsoft.Json.JsonConvert.SerializeObject(new CoreResult<string>(APIResultCode.ValidateError, "别一天天乱搞，我这啥也没有。")));

            //var logger = ((ILoggerFactory)context.RequestServices.GetService(typeof(ILoggerFactory)))
            //    .CreateLogger("API.PerformanceLog");
            //logger.LogInformation($"{context.Request.Method}, Path:{context.Request.Path}, ElapsedMilliseconds:{profiler.ElapsedMilliseconds}ms, {context.Request.ContentType} {context.Response.StatusCode}");
        }
    }
}